<?php



require_once __DIR__ . '/vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;


$connection = new AMQPStreamConnection('192.168.10.10',5672,'admin','admin');
$channel = $connection ->channel();

$ttl_time = 15000;

//创建超时队列 和交换机 
$channel->exchange_declare('delay_exchange3','direct',false,false,false);
$channel->queue_declare('delay_queue3',false,true,false,false);
//绑定  
$channel->queue_bind('delay_queue3','delay_exchange3','delay_exchange3');


//创建定时   
$table = new AMQPTable();
$table->set('x-dead-letter-exchange', 'delay_exchange3'); // 表示过期后由哪个exchange处理
$table->set('x-dead-letter-routing-key','delay_exchange3');  //死信路由key
$table->set('x-message-ttl', $ttl_time); //存活时长   下面的过期时间不能超过
$channel->exchange_declare('cache_exchange3','direct',false,false,false);
$channel->queue_declare('cache_queue3',false,true,false,false,false,$table);
//绑定  
$channel->queue_bind('cache_queue3','cache_exchange3','cache_exchange3');

sendMessage('蜗牛巢 致力于分享原创高质量文章',$channel);

function sendMessage($message = '',$channel)
{
    $amqp_channel = $channel;
    for ($i = 1; $i <= 10; $i++) {
        $messages = new AMQPMessage($message, [
            'expiration' => intval($ttl_time),
            'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT
        ]);
        $amqp_channel->basic_publish($messages, 'cache_exchange3', 'cache_exchange3');
        sleep(2);
        echo date('Y-m-d H:i:s') . " Sent " . $message . PHP_EOL;
    }
}

$channel->close();
$connection->close();

